import React, { useRef, useState } from 'react';
import {
  Box,
  Button,
  Typography,
  CircularProgress,
  Alert,
} from '@mui/material';
import {
  CloudUpload,
  Image,
  VideoFile,
} from '@mui/icons-material';

interface MediaUploaderProps {
  accept: string;
  onUpload: (file: File) => Promise<void>;
  loading?: boolean;
  buttonText?: string;
  helperText?: string;
  maxSize?: number; // MB
}

export const MediaUploader: React.FC<MediaUploaderProps> = ({
  accept,
  onUpload,
  loading = false,
  buttonText = '上传文件',
  helperText,
  maxSize = 50, // 默认50MB
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [error, setError] = useState<string | null>(null);
  const [dragOver, setDragOver] = useState(false);

  const validateFile = (file: File): string | null => {
    // 检查文件大小
    if (file.size > maxSize * 1024 * 1024) {
      return `文件大小不能超过 ${maxSize}MB`;
    }

    // 检查文件类型
    const acceptTypes = accept.split(',').map(type => type.trim());
    const isValidType = acceptTypes.some(type => {
      if (type === 'image/*') return file.type.startsWith('image/');
      if (type === 'video/*') return file.type.startsWith('video/');
      return file.type === type || file.name.toLowerCase().endsWith(type.replace('*', ''));
    });

    if (!isValidType) {
      return '不支持的文件类型';
    }

    return null;
  };

  const handleFileSelect = async (file: File) => {
    setError(null);
    
    const validationError = validateFile(file);
    if (validationError) {
      setError(validationError);
      return;
    }

    try {
      await onUpload(file);
    } catch (err) {
      setError('上传失败，请稍后重试');
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
    // 清空input值，允许重复选择同一文件
    event.target.value = '';
  };

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    setDragOver(true);
  };

  const handleDragLeave = (event: React.DragEvent) => {
    event.preventDefault();
    setDragOver(false);
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    setDragOver(false);
    
    const files = Array.from(event.dataTransfer.files);
    if (files.length > 0) {
      handleFileSelect(files[0]);
    }
  };

  const getIcon = () => {
    if (accept.includes('image')) return <Image sx={{ fontSize: 48, color: 'text.secondary' }} />;
    if (accept.includes('video')) return <VideoFile sx={{ fontSize: 48, color: 'text.secondary' }} />;
    return <CloudUpload sx={{ fontSize: 48, color: 'text.secondary' }} />;
  };

  return (
    <Box>
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        onChange={handleFileChange}
        style={{ display: 'none' }}
      />
      
      <Box
        sx={{
          border: 2,
          borderColor: dragOver ? 'primary.main' : 'grey.300',
          borderStyle: 'dashed',
          borderRadius: 2,
          p: 3,
          textAlign: 'center',
          cursor: loading ? 'not-allowed' : 'pointer',
          bgcolor: dragOver ? 'action.hover' : 'transparent',
          transition: 'all 0.2s ease',
          '&:hover': {
            borderColor: loading ? 'grey.300' : 'primary.main',
            bgcolor: loading ? 'transparent' : 'action.hover',
          },
        }}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={loading ? undefined : handleButtonClick}
      >
        {loading ? (
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
            <CircularProgress size={48} />
            <Typography color="text.secondary">上传中...</Typography>
          </Box>
        ) : (
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
            {getIcon()}
            <Box>
              <Button
                variant="contained"
                startIcon={<CloudUpload />}
                onClick={handleButtonClick}
                disabled={loading}
              >
                {buttonText}
              </Button>
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                或拖拽文件到此处
              </Typography>
            </Box>
          </Box>
        )}
      </Box>

      {helperText && (
        <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
          {helperText}
        </Typography>
      )}

      {error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {error}
        </Alert>
      )}
    </Box>
  );
}; 